package com.um.jdy.app.shop.scheduled;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.um.jdy.app.shop.manager.ShopOrderManager;
import com.um.jdy.common.market.entity.po.Group;
import com.um.jdy.common.market.service.GroupService;
import com.um.jdy.common.shop.entity.po.Order;
import com.um.jdy.common.shop.enums.OrderEnum;
import com.um.jdy.common.shop.service.ShopOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 订单定时任务
 * @author renjunwei
 * @date 2020/10/25 14:43
 */
@Slf4j
@Component
@Profile({"!dev"})
public class ShopOrderTask {

    @Autowired
    private GroupService groupService;

    @Autowired
    private ShopOrderService shopOrderService;

    @Autowired
    private ShopOrderManager shopOrderManager;


    /**
     * 3小时取消团
     * Redisson队列失效时触发，定时任务有延迟
     */
    @Async
    @Scheduled(fixedRate = 300000, initialDelay = 60000)
    public void cancelGroup() {

        List<Group> groupList = groupService.getRows(new String[]{"status"}, new Object[]{OrderEnum.GroupStatus.Unopen.name()});

        DateTime now = DateUtil.date();

        for (Group group : groupList) {
            //取消时间：创建拼团时间+3小时
            Date cancelTime = DateUtil.offsetHour(group.getCreateTime(), 3);

            if (now.isAfter(cancelTime)) {
                try {
                    shopOrderManager.closeGroup(group.getMarketGroupId());
                    log.info("定时任务关闭拼团:{}", group.getMarketGroupId());
                } catch (Exception e) {
                    log.error("定时任务关闭拼团错误", e);
                }
            }
        }
    }

    /**
     * 30分钟未付款自动取消订单
     * Redisson队列失效时触发，定时任务有延迟
     */
    @Async
    @Scheduled(fixedRate = 300000, initialDelay = 120000)
    public void cancelOrder() {

        List<Order> orderList = shopOrderService.getRows(new String[]{"status"}, new Object[]{OrderEnum.Status.UnPay.name()});

        DateTime now = DateUtil.date();

        for (Order order : orderList) {

            //取消时间：创建订单时间+30分钟
            Date cancelTime = DateUtil.offsetMinute(order.getCreateTime(), 30);

            //秒杀活动订单5分钟取消
            // if(ActivityEnum.Type.Seckill.name().equals(order.getType())){
            //     cancelTime = DateUtil.offsetMinute(DateUtil.parse(StringUtil.getTrim(order.get("create_time"))), 5).getTime();
            // }

            if (now.isAfter(cancelTime)) {
                try {
                    shopOrderManager.cancel(order.getShopOrderId(), order.getMemberUserId());
                    log.info("定时任务取消订单:{}", order.getOrderNo());
                }  catch (Exception e) {
                    log.error("定时任务取消订单错误", e);
                }
            }
        }
    }

    /**
     * 发货七天自动确认收货
     */
    @Async
    @Scheduled(fixedRate = 300000, initialDelay = 180000)
    public void confirmReceipt() {

        List<Order> orderList = shopOrderService.getRows(new String[]{"status"}, new Object[]{OrderEnum.Status.UnReceive.name()});

        DateTime now = DateUtil.date();

        for (Order order : orderList) {

            //取消时间：创建订单时间+30分钟
            Date cancelTime = DateUtil.offsetDay(order.getCreateTime(), 7);

            if (now.isAfter(cancelTime)) {
                try {
                    shopOrderManager.receive(order.getShopOrderId(), order.getMemberUserId());
                    log.info("定时任务确认收货:{}", order.getOrderNo());
                }  catch (Exception e) {
                    log.error("定时任务确认收货错误", e);
                }
            }
        }
    }


//    /**
//     * 收货七天自动五星好评
//     */
//    @Scheduled(cron = "0 */1 * * * ?")
//    public void createComment(){
//
//        List<Map> commentTemplate = commonService.queryList(TableName.MALL_COMMENT_TEMPLATE,new Object[]{},new Object[]{});
//        if(commentTemplate.size() > 0){
//
//            //当前时间-7天
//            String datetime = DateUtil.offsetDay(DateUtil.date(),-7).toString();
//
//            List<Map> unevaluationOrderList = commonService.queryListBySQLName("get_auto_comment_order_list", new String[]{datetime});
//
//            for (Map order : unevaluationOrderList) {
//
//                List<Map> orderGoodsList = commonService.queryList(TableName.MALL_ORDER_GOODS,new String[]{"mall_order_id"},new Object[]{order.get("mall_order_id")});
//                for(Map orderGoods : orderGoodsList){
//                    orderGoods.putAll(commentTemplate.get(RandomUtil.randomInt(0,commentTemplate.size())));
//                    orderGoods.put("thumbs", JSONUtil.parseJSONToList(StringUtil.getTrim(orderGoods.get("thumbs"))));
//                }
//
////                orderService2.createComment(StringUtil.getTrim(order.get("mall_order_id")),orderGoodsList, CommentReviewStatus.PASSED.getKey());
//                log.info("收货7天后系统自动评价，订单号：{}", StringUtil.getTrim(order.get("order_no")));
//            }
//        }
//
//    }

}